﻿using KeDa2025_.Utils;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Data;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KeDa2025_
{
    public partial class detail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UpdateReadCount();
            }
        }

        private void UpdateReadCount()
        {
            int noteId = Convert.ToInt32(Request["id"]);
            DbHelper.Query("update notes set read_count=read_count+1 where id=" + noteId);
        }
        #region 日志信息绑定
        public string InitNote()
        {

            //1.获取querystring传值  日志id
            int noteId = Convert.ToInt32(Request.QueryString["id"]);
            //2.根据日志id去数据库查询日志信息
            string sql = string.Format("select * from notes where id={0}", noteId);
            DataSet ds = DbHelper.Query(sql);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                // 将完整的 DataRow 存储到 Session 中  
                Session["Note"] = ds.Tables[0].Rows[0];
            }
            DataRow noteRow = (DataRow)Session["Note"];
            //3.进行替换
            int noteid = Convert.ToInt32(Request["id"]);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(" <div class=\"show\">");
            stringBuilder.Append(string.Format("<h2>{0}</h2>", noteRow["title"]));
            stringBuilder.Append(string.Format("<div class=\"show_time\">发布时间: {0} 阅读: {1}</div>", noteRow["create_time"], noteRow["read_count"]));
            stringBuilder.Append("<p>");
            stringBuilder.Append(string.Format("内容:{0}", noteRow["detail"]));
            stringBuilder.Append("</p>");
            stringBuilder.Append("  </div>");
            return stringBuilder.ToString();


        }
        #endregion


        #region 评论信息加载
        public string InitComment()
        {
            //1.根据用户点击的日志id查询他的评论
            int noteID = Convert.ToInt32(Request["id"]);
            int publicUserId = 0;//发布人id
            int loginUserId = Convert.ToInt32(((DataRow)Session["User"])["id"]);//登录人
            DataSet dsNote = DbHelper.Query("select * from notes where id=" + noteID);
            if (dsNote.Tables[0].Rows.Count > 0)
            {
                publicUserId = Convert.ToInt32(dsNote.Tables[0].Rows[0]["user_id"]);
            }
            DataRow userRow = (DataRow)Session["User"];
            DataSet ds = DbHelper.Query("select c.*,u.img_url,u.account from comments c inner join users u on u.id=c.user_id where c.note_id=" + noteID);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                stringBuilder.Append("<div class=\"pinglun\">");
                stringBuilder.Append("      <div class=\"pl_left left\">");
                stringBuilder.Append($"      <img src=\"{ds.Tables[0].Rows[i]["img_url"]}\">");
                stringBuilder.Append("        </div>");
                stringBuilder.Append("            <div class=\"pl_right left\">");
                stringBuilder.Append($"       <p class=\"p_a\"><span>{i + 1}楼</span> {ds.Tables[0].Rows[i]["account"]} 评论时间: {ds.Tables[0].Rows[i]["create_time"]}</p>");
                stringBuilder.Append($"   <p>{ds.Tables[0].Rows[i]["detail"]} <a onclick=\"alertReply({ds.Tables[0].Rows[i]["id"]})\">回复</a>&nbsp;&nbsp;");
                int commentUserId = Convert.ToInt32(ds.Tables[0].Rows[i]["user_id"]);//当前遍历行 评论人
                if (loginUserId == publicUserId || loginUserId == commentUserId)
                {
                    stringBuilder.Append($"<a onclick='delComment({ds.Tables[0].Rows[i]["id"]})'>删除评论</a>");
                }
                stringBuilder.Append("</p>");
                stringBuilder.Append(" <div class=\"reply\">");
                stringBuilder.Append("<ul id=\"ul1\">");
                DataSet dsReply = DbHelper.Query("select r.*,u.account,u.img_url from replys r inner join users u on u.id=r.user_id where r.comment_id=" + ds.Tables[0].Rows[i]["id"]);
                if (dsReply.Tables[0].Rows.Count > 0)
                {
                    for (int j = 0; j < dsReply.Tables[0].Rows.Count; j++)
                    {
                        stringBuilder.Append(" <li>");
                        stringBuilder.Append($" <img src=\"{dsReply.Tables[0].Rows[j]["img_url"]}\" width=\"35\" class=\"left\">");
                        stringBuilder.Append(" <p class=\"left\">");
                        stringBuilder.Append($" <span>{dsReply.Tables[0].Rows[j]["account"]}&nbsp;</span>{dsReply.Tables[0].Rows[j]["detail"]}<br>");
                        stringBuilder.Append($" {dsReply.Tables[0].Rows[j]["create_time"]}");
                        int replyUserId = Convert.ToInt32(dsReply.Tables[0].Rows[j]["user_id"]);//回复人
                        if (loginUserId == publicUserId || loginUserId == replyUserId)
                        {
                            stringBuilder.Append($"<a onclick='delReply({dsReply.Tables[0].Rows[j]["id"]})' href=\"#\"><span class=\"glyphicon glyphicon-trash\"></span>删除</a>");
                        }
                        stringBuilder.Append("    </p>");
                        stringBuilder.Append("  </li>");
                    }
                }

                stringBuilder.Append(" </ul>");
                stringBuilder.Append("   </div>");
                stringBuilder.Append(" </div>");
            }
            return stringBuilder.ToString();
        }
    
        #endregion

        protected void btnComment_Click(object sender, EventArgs e)
        {


            // 从 Session 获取 userId
            DataRow userRow = (DataRow)Session["User"];
            int userId = Convert.ToInt32(userRow["id"]); // 从 userRow 中获取 id
           

            // 从请求中获取 noteId
            int noteId = Convert.ToInt32(Request["id"]);
            DateTime createTime = DateTime.Now;

            // 获取评论内容
            string detail = txtComment.Value.Trim();
            if (string.IsNullOrEmpty(detail))
            {
                // 如果评论内容为空，提示用户并返回
                Response.Write("<script>alert('评论内容不能为空！');</script>");
                return;
            }

            // 插入评论到数据库

            string sql = string.Format("INSERT INTO comments (user_id,note_id,detail,create_time) VALUES ('{0}', '{1}', '{2}', '{3}')", userId, noteId, detail, createTime);
            // 建立数据库连接
            string connectionString = "server=localhost;user id=zmy2;password=zmy20020525;database=forum;";
            MySqlConnection connection = new MySqlConnection(connectionString);

            // 创建MySQLCommand对象
            MySqlCommand cmd = new MySqlCommand(sql, connection);

            // 执行SQL语句并获取结果
            connection.Open();
            int flag = cmd.ExecuteNonQuery();
            connection.Close();
            if (flag > 0)
                Response.Write("<script>alert('评论成功');window.location.href='index.aspx'</script>");
            // 刷新页面以显示最新评论
          
            Response.Redirect("detail.aspx?id=" + noteId);


        }

       
    }
}